package com.yeskery.nut.script.function.extend.memory;

import com.yeskery.nut.core.Execution;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.extend.memory.MemoryPlugin;
import com.yeskery.nut.extend.memory.Storage;
import com.yeskery.nut.plugin.BindContext;
import com.yeskery.nut.script.function.BaseMultiParamFunction;

/**
 * {@link com.yeskery.nut.extend.memory.MemoryPlugin} 插件支持的基于本地存储的函数
 * @author sprout
 * @version 1.0
 * 2022-07-19 10:36
 */
public abstract class BaseMemoryPluginSupportFunction extends BaseMultiParamFunction {

    /** 锁对象 */
    private final static Object LOCK = new Object();

    /** 基于内存的存储对象 */
    private volatile Storage storage;

    /**
     * 获取基于内存的存储对象
     * @return 基于内存的存储对象
     */
    public Storage getStorage() {
        if (storage == null) {
            synchronized (LOCK) {
                if (storage == null) {
                    BindContext bindContext = ((Execution) getNutApplication().getNutWebConfigure().getDispatcher()).getBindContext();
                    storage = bindContext.getObject(Storage.class);
                    if (storage == null) {
                        MemoryPlugin memoryPlugin = new MemoryPlugin();
                        getNutApplication().getNutWebConfigure().getPluginManager().registerPlugin(memoryPlugin);
                        memoryPlugin.bind(bindContext);
                        storage = bindContext.getObject(Storage.class);
                        if (storage == null) {
                            throw new NutException("MemoryPlugin Config Fail, Storage Create Fail.");
                        }
                    }
                }
            }
        }
        return storage;
    }
}
